import { ITEM_RENDER_EVT } from "element-plus/es/components/virtual-list/src/defaults";
import { defineStore } from "pinia";
import { computed, ref, reactive } from "vue";
import permissionCorrespondence from "../../config/permissionCorrespondenceTable";
import _ from "lodash";

export const useUserStore = defineStore(
  "user",
  () => {
    let userInfo = reactive({
      token: "",
      userName: "",
      expire: "",
    });
    let currentUserInfo = computed(() => {
      return userInfo;
    });

    let perm = ref([]);
    let currentPerm = computed(() => {
      return perm;
    });
    let closePerm = computed(() => {
      const closePerm = perm.value
        .filter((i) => i.value === 0)
        .map((item) => {
          return item.permissions;
        });

      return closePerm;
    });

    //权限信息
    let permissions = ref([]);
    let currentPermissions = computed(() => {
      let permList = _.cloneDeep(permissions);
      const closePerm = perm.value
        .filter((i) => i.value === 0)
        .map((item) => {
          return item.permissions;
        });

      // 若为空直接return出去
      if (closePerm.length === 0) {
        return permList;
      }

      //如果是perm.c为0，则清除权限表并return
      if (closePerm.includes("web_all")) {
        permList.value = ["web_all"];
        return permList;
      }

      permList.value = permList.value.filter(
        (item) => closePerm.findIndex((i) => item.indexOf(i) > -1) < 0
      );
      return permList;
    });

    // 币种列表
    let coinListInfo = ref([]);

    let currentCoinListInfo = computed(() => {
      return coinListInfo;
    });
    function setCoinListInfo(data) {
      coinListInfo.value = data;
    }

    function setPerm(data) {
      permissionCorrespondence.forEach((item, index) => {
        item.value = data[item.key];
      });
      perm.value = permissionCorrespondence;
    }
    // 设置权限信息
    function setPermissions(data) {
      permissions.value = data;
    }
    // 清楚权限
    function clearPermissions() {
      permissions.value = [];
      perm.value = [];
      coinListInfo.value = [];
    }

    // 设置用户信息
    function setUserInfo(data) {
      const { token, name, expire } = data;
      (userInfo.token = token),
        (userInfo.userName = name),
        (userInfo.expire = expire);
    }

    function clearUserInfo() {
      (userInfo.token = ""), (userInfo.userName = ""), (userInfo.expire = "");
    }

    return {
      userInfo,
      currentUserInfo,
      setUserInfo,
      clearUserInfo,
      permissions,
      currentPermissions,
      perm,
      currentPerm,
      closePerm,
      setPerm,
      setPermissions,
      clearPermissions,
      coinListInfo,
      currentCoinListInfo,
      setCoinListInfo,
    };
  },
  {
    persist: true,
  }
);
